
package com.agilerabbit.tools;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.util.Log;


public class XmlParserRobot {
	
	public String getXmlString(String url) {
        String retVal = null; 
        try {
        	
        	HttpPost post = new HttpPost(url);
            DefaultHttpClient client = new DefaultHttpClient();         
            HttpResponse httpResponse = client.execute(post);        
            HttpEntity httpEntity = httpResponse.getEntity();
            retVal = EntityUtils.toString(httpEntity,"UTF-8");
 
        } catch (Exception ex) {
            ex.printStackTrace();
        
        }
        
        return retVal;
    }
	
	public String getXmlString(InputStream inputStream)
	{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();				
	
		
		byte buf[] = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(buf)) != -1) {
				outputStream.write(buf, 0, len);
			}
			outputStream.close();
			inputStream.close();
		} catch (IOException e) {

		}

		String xmlString = outputStream.toString();		
		return xmlString;
		
	}
	
	public Document getDomElement(String xml){
        Document document = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
 
            DocumentBuilder db = dbf.newDocumentBuilder(); 
            InputSource is = new InputSource();
            is.setEncoding("UTF-8");
            is.setCharacterStream(new StringReader(xml));
            document = db.parse(is);  
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } 
            return document;
    }
	
	public String getNodeText(Element item, String str) {
		
	    NodeList n = item.getElementsByTagName(str);
	    return this.getElementValue(n.item(0));
	}
	 
	public final String getElementValue( Node elem ) {
	         Node child;
	         if( elem != null){
	             if (elem.hasChildNodes()){
	                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                     if( child.getNodeType() == Node.TEXT_NODE ||  child.getNodeType() == Node.CDATA_SECTION_NODE ){
	                         return child.getNodeValue();
	                     }
	                 }
	             }
	         }
	         return "";
	  } 
	

}
